﻿using AvalSqlIndexManager.Models;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Platform.Storage; // 用于 SaveFileDialog

namespace AvalSqlIndexManager.ViewModels
{
    public class IndexEditViewModel : ViewModelBase
    {
        public ReactiveCommand<Unit, TableIndex?> EditCommitCommand { get; }

        public ReactiveCommand<TopLevel, Unit> SaveFileCommand { get; }

        private TableIndex? _editingNode;

        public TableIndex? EditingNode
        {
            get => _editingNode;
            set
            {
                this.RaiseAndSetIfChanged(ref _editingNode, value);
                this.FieldsName = _editingNode!.FieldsName;
            }
        }

        private string? _fieldsName;
        public string? FieldsName
        {
            get
            {
                return _fieldsName;
            }
            set
            {
                this.RaiseAndSetIfChanged(ref _fieldsName, value);
                this._editingNode!.FieldsName = _fieldsName ?? string.Empty;
            }
        }

        private string? _sqlIndex;
        public string? SqlIndex
        {
            get => _sqlIndex;
            set => this.RaiseAndSetIfChanged(ref _sqlIndex, value);
        }

        public IndexEditViewModel()
        {
            this.WhenAnyValue(x => x.FieldsName)                
               .Throttle(TimeSpan.FromMilliseconds(400))
               .ObserveOn(RxApp.MainThreadScheduler)
               .Subscribe(DoSearch!);

            //_editingNode = new Node();
            EditCommitCommand = ReactiveCommand.Create(() =>
            {
                return _editingNode;
            });

            SaveFileCommand = ReactiveCommand.CreateFromTask< TopLevel,Unit>(SaveAsync);
            //EditingNode = new Node { FieldNames = "Field1", TableName = "TableName" };
        }

        private void DoSearch(object s)
        {
            if (this.EditingNode != null)
                SqlIndex = this.EditingNode.BuildCreateSql();
        }

        private async Task<Unit> SaveAsync(TopLevel topLevel)
        {
            if (this.EditingNode == null)
                return Unit.Default;
            // 从当前控件获取 TopLevel。或者，您也可以使用 Window 引用。
            //var topLevel = TopLevel.GetTopLevel(this);

            // 启动异步操作以打开对话框。
            var file = await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
            {
                Title = "Save Text File",
                SuggestedFileName = string.Format("{0}.sql", this.EditingNode.GetIndexName())
            });

            if (file is not null)
            {
                // 打开文件的写入流。
                await using var stream = await file.OpenWriteAsync();
                using var streamWriter = new StreamWriter(stream);
                // 将一些内容写入文件。
                await streamWriter.WriteLineAsync(this.EditingNode.BuildCreateSql());
            }
            return Unit.Default;
        }
    }
}
